package com.avic.rong.search.fragment.searchResultFragments;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.BaseFragment;
import com.avic.rong.R;
import com.avic.rong.goodsSort.adapter.secondListAdapter.GoodsSortTsSxShowRvAdapter;
import com.avic.rong.goodsSort.api.secondListApi.GoodsSortSearchAllTsSxApi;
import com.avic.rong.goodsSort.bean.showRvBean.GoodsSortSearchAllBzBean;
import com.avic.rong.goodsSort.bean.showRvBean.GoodsSortSearchTsSxBean;
import com.avic.rong.search.MessageEvent;
import com.avic.rong.search.activity.SearchResaultActivity;
import com.avic.rong.search.adapter.searchResultFragmentsAdapters.SearchVpGoodsRvAdapter;
import com.avic.rong.search.api.secondViewApi.SearchHomeQuanBuApi;
import com.avic.rong.userOrder.api.AddCarApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DeviceUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchGoodsFragment extends BaseFragment implements SearchVpGoodsRvAdapter.SearchHomePageGoodsListener, GoodsSortTsSxShowRvAdapter.GoodsTsSxRvListener {

    @BindView(R.id.search_Goods_Rv)
    RecyclerView searchGoodsRv;
    Unbinder unbinder;
    @BindView(R.id.search_vp_goods_tv)
    TextView searchVpGoodsTv;
    @BindView(R.id.beijing_image)
    ImageView beijing_image;
    @BindView(R.id.search_fragment_goods_SmartRefreshLayout)
    SmartRefreshLayout searchFragmentGoodsSmartRefreshLayout;

    private List<GoodsSortSearchTsSxBean.DataBean> tsSxList = new ArrayList<>();
    private GoodsSortTsSxShowRvAdapter showSxRvAdapter;
    private View view;
    private SearchVpGoodsRvAdapter adapter;
    private String currentText = "GJB";
    private List<GoodsSortSearchAllBzBean.DataBean> list = new ArrayList<>();
    private static int pageNo = 1;

    public SearchGoodsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_search_goods, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        list.clear();
        tsSxList.clear();
        initBzData(currentText,pageNo);
        searchGoodsRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new SearchVpGoodsRvAdapter(getContext(), list);
        searchGoodsRv.setAdapter(adapter);
        setRefresh();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void cha(MessageEvent msg){
        if (msg.getType()!=null){
            if (msg.getType().equals("tsSure")){
                String attrPro = msg.getMessage();
                initGoodsSureData(attrPro);
            }else {
                return;
            }
        }

    }

    private void initGoodsSureData(String attrPro) {
        GoodsSortSearchAllTsSxApi searchAllSxApi = new GoodsSortSearchAllTsSxApi((SearchResaultActivity)getActivity(), searchAllTsSxListener, 1, 2, attrPro);
        searchAllSxApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(searchAllSxApi);
    }
    //获取图书时间数据
    HttpOnNextListener<BaseResultEntity> searchAllTsSxListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals("200")) {

                Log.e("cjx", "图书time数据：" + subjects.getMsg());
                return;
            }
            ArrayList<GoodsSortSearchTsSxBean> beans = (ArrayList<GoodsSortSearchTsSxBean>) subjects.getData();
            tsSxList.addAll(beans.get(1).getData());
            //主界面数据
            searchGoodsRv.setLayoutManager(new LinearLayoutManager(getActivity()));
            showSxRvAdapter = new GoodsSortTsSxShowRvAdapter(getActivity());
            searchGoodsRv.setAdapter(showSxRvAdapter);
            showSxRvAdapter.setGoodsTsSxListener(SearchGoodsFragment.this);
            showSxRvAdapter.setTsSxList(tsSxList);
            showSxRvAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {

        }
    };


    private void setRefresh() {
        searchFragmentGoodsSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                list.clear();
                initBzData(currentText,pageNo);
                searchFragmentGoodsSmartRefreshLayout.finishRefresh(1000);
            }
        });
        searchFragmentGoodsSmartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                ++pageNo;
                initBzData(currentText,pageNo);
                searchFragmentGoodsSmartRefreshLayout.finishLoadMore(1000);
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        currentText = SearchResaultActivity.nowSearchStr;
        Log.e("cjx", "SearchQuanBuFragment--------currentText:" + currentText);
    }

    private void initBzData(String keyword,int pageNo) {
        SearchHomeQuanBuApi searchAllApi = new SearchHomeQuanBuApi((BaseActivity) getActivity(), searchHomeQuanBuListener, "goods", 1, 2, keyword, pageNo, 10);
        Log.e("cjx", "bzkeyWord:" + keyword);
        searchAllApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(searchAllApi);
    }

    //获取标准数据监听
    HttpOnNextListener<BaseResultEntity> searchHomeQuanBuListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals("200")) {
                Log.e("cjx", "biaozhun数据：" + subjects.getMsg());
                return;
            }
            ArrayList<GoodsSortSearchAllBzBean> searchHomeQuanBuList = (ArrayList<GoodsSortSearchAllBzBean>) subjects.getData();
            list.addAll(searchHomeQuanBuList.get(1).getData());
            if (list.size() > 0) {
                searchGoodsRv.setVisibility(View.VISIBLE);
                searchVpGoodsTv.setVisibility(View.GONE);
                beijing_image.setVisibility(View.GONE);
                 adapter.notifyDataSetChanged();
                adapter.setListener(SearchGoodsFragment.this);
                searchGoodsRv.setAdapter(adapter);
            } else {
                searchGoodsRv.setVisibility(View.GONE);
                searchVpGoodsTv.setVisibility(View.VISIBLE);
                beijing_image.setVisibility(View.VISIBLE);
            }

        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
        }
    };


    @Override
    protected void initView() {

    }

    @Override
    protected void addListener() {

    }

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    public void searchHomePageGoodsAddCar(String skuStr) {
        AddCar(skuStr);
    }

    private void AddCar(String skuStr) {
        Log.e("cjx", "skuStr:" + skuStr);

            Map<String, String> map = new HashMap<>();
            map.put("skuStr", skuStr);
            map.put("orderType", 4 + "");
//            是否再次购买（0/1）
            map.put("buyAgain", 0 + "");
        if (SharedPreferencesUtil.isLogin()) {
            map.put("token", SharedPreferencesUtil.getLoginToken());
        }
            map.put("deviceId", DeviceUtils.getIMEString(context));
            final AddCarApi addCarApi = new AddCarApi((SearchResaultActivity) getActivity(), simpleOnNextListenerAddCar);
            addCarApi.setCache(false);
            addCarApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(addCarApi);

    }

    //添加购物车
    HttpOnNextListener simpleOnNextListenerAddCar = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                return;
            }
            ToastTools.showToast("添加成功");
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    @Override
    public void addTsSxCar(String skuStr) {
        AddCar(skuStr);
    }
}
